//
//  Register_Confirm_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 20-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Register_Confirm_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "dao.h"

@interface Register_Confirm_ViewController ()

@end

@implementation Register_Confirm_ViewController

@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize lblNombreCompleto, lblDireccion, lblCiudad, lblComuna, lblCelular, lblReferencia, lblFormaPago;
@synthesize lblSubTotal, lblDespacho, lblTotal;
@synthesize viewPicker, pickerView, dataArray, dataArrayId, json, showPickerFechaEntrega, strFechaEntrega;

// Number of components.
//------------------------------------------------------------------------------------------------------------------
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    NSLog(@"numberOfRowsInComponent =%lu", (unsigned long)[dataArray count]);
    
    return [dataArray count];
}

// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    NSLog(@"titleForRow=%@", [dataArray objectAtIndex: row]);
    
    return [dataArray objectAtIndex: row];
}

// Do something with the selected row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    NSString *strFechaDespacho = [dataArrayId objectAtIndex: row];

    NSString *strFechaDespachoFormato = [dataArray objectAtIndex: row];

    if ([strFechaDespacho  isEqual: @"0"]) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Debe definir una fecha de entrega para su compra."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

    }else{

        NSLog(@"strFechaDespacho =%@", strFechaDespacho);
        NSLog(@"strFechaDespachoFormato =%@", strFechaDespachoFormato);
        
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        
        [prefs setObject:strFechaDespacho forKey:@"strFechaEntrega"];
        
        [prefs setObject:strFechaDespachoFormato forKey:@"strFechaEntregaDescription"];
        
        //Setear el Label
        strFechaEntrega.text = strFechaDespachoFormato;
    }
    
}

//------------------------------------------------------------------------------------------------------------------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"count=%lu", (unsigned long)[_dataArraySearch count]);
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
//  cell.imgImageView.image = [UIImage imageNamed:@"img_maletin.png"];
    cell.lblTrademark.text = objCell.strTrademark;
    cell.lblTitleLabel.text = objCell.strTitleLabel;
    cell.lblQty.text = objCell.strQty;
    cell.lblPrice.text = objCell.strPrice;
    cell.lblSubtitleLabel.text = objCell.strSubtitleLabel;
   
    //-------------------------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"3_%@.jpg", objCell.strIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    
    [cell.imgImageView setImage:image];
    //-------------------------------------------------------------------------------------------------
    
    return cell;
}

- (void) retrieveDataSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser = [objDAO obtainCurrentIdUser];
    NSMutableArray *ArrayProducts;
    NSArray *ArrayProduct;
    
    if (intIdUser == -1) {
        intIdUser = 1;
    }
    
    ArrayProducts = [objDAO obtainProductsShoppingCart:intIdUser];
    
    for (int i = 0; i<ArrayProducts.count; i++)
    {
        ArrayProduct = ArrayProducts[i];
        /*
         strIdUsuario           = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
         strIdProducto          = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
         strIdSKU               = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
         strDescripcionProd     = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
         strIdMarca             = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
         strDescripcionMarca    = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
         strCantidad            = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
         strNeto                = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
         strIva                 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
         strTotal               = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];
         */
        
        NSString *strTitleLabel = ArrayProduct[3]; //@"Cartera Desigual Fucsia, ideal para paseos livianos y comodos en todo clima. De textura liviana, materiales finos.";
        NSString *strSubtitleLabel = @"";
        NSString *strTrademark = ArrayProduct[5]; //@"DESIGUAL";
        NSString *strIdmark = ArrayProduct[4];
        
        NSString *strSKU = ArrayProduct[2];
        NSString *strIdProducto = ArrayProduct[1];
        NSString *strReviews = @"";
        NSString *strPrice = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayProduct[9] doubleValue]]  ]; //@"$ 26.580 c/u";
        NSString *strOfferPrice = @"";
        NSString *strPriceDuplicated = @"";
        NSString *strDiscount = @"";
        NSString *strOfferTime = @"";
        
        NSString *strCantidadTmp = [NSString stringWithFormat:@"%.0f", [ArrayProduct[6] floatValue] ];   //%.2f
        
        NSString *strQty = strCantidadTmp;
        
        strSubtitleLabel = strSKU; //**Parche para mostrar la unidad de empaque
        
        classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
        
        [_dataArraySearch addObject:objCell];
    }
    
    [self.tableViewSearch reloadData];
    //------------------------------------------
}

- (NSString *) obtenerRutaBD{
    NSString *dirDocs;
    NSArray *rutas;
    NSString *rutaBD;
    
    rutas = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    dirDocs = [rutas objectAtIndex:0];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    rutaBD = [[NSString alloc] initWithString:[dirDocs stringByAppendingPathComponent:@"ecommerce.sqlite"]];
    
    if([fileMgr fileExistsAtPath:rutaBD] == NO){
        [fileMgr copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ecommerce.sqlite"] toPath:rutaBD error:NULL];
    }
    
    return rutaBD;
}

- (void) retrieveClient{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    NSString *ubicacionDB = [self obtenerRutaBD];
    
    if(!(sqlite3_open([ubicacionDB UTF8String], &bd) == SQLITE_OK)){
        NSLog(@"Database connection failure irn");
    }
    
    NSString *sqlSelect = [NSString stringWithFormat:@"SELECT MC_RUT_CLIENTE, MC_DIGITO, MC_NOMBRE_COMPLETO, MC_APELLIDOS, MC_TELEFONO, MC_DIA, MC_MES, MC_ANO, MC_SEXO, MCLI_FORMA_PAGO FROM ECOM_MAESTRO_CLIENTES WHERE USIS_ID = %i", intIdUser];
    
    const char *sentenciaSQL = [sqlSelect UTF8String];
    
    sqlite3_stmt *sqlStatement;
    
    if(sqlite3_prepare_v2(bd, sentenciaSQL, -1, &sqlStatement, NULL) != SQLITE_OK){
        NSLog(@"Exception to prepare statement");
    }
    
    NSString *strRutCliente, *strIdComuna, *strDigito, *strNombreCompleto, *strApellidos, *strTelefono, *strDia, *strMes, *strAno, *strSexo, *strFormaPago;
    
    while(sqlite3_step(sqlStatement) == SQLITE_ROW){
        
        strRutCliente = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
        
        strDigito = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
        
        strNombreCompleto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
        
        strApellidos = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
        
        strTelefono = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
        
        strDia = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
        
        strMes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
        
        strAno = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
        
        strSexo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
        
        strFormaPago = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];
    }
    
    NSLog(@"strRutCliente     =%@", strRutCliente);
    NSLog(@"strIdComuna       =%@", strIdComuna);
    NSLog(@"strDigito         =%@", strDigito);
    
    NSLog(@"strNombreCompleto =%@", strNombreCompleto);
    NSLog(@"strApellidos      =%@", strApellidos);
    NSLog(@"strTelefono       =%@", strTelefono);
    
    NSLog(@"strDia =%@", strDia);
    NSLog(@"strMes =%@", strMes);
    NSLog(@"strAno =%@", strAno);
    
    NSLog(@"strSexo=%@", strSexo);
    NSLog(@"strFormaPago=%@", strFormaPago);
    
    lblNombreCompleto.text = [NSString stringWithFormat:@"%@ %@", strNombreCompleto, strApellidos];
    
    lblCelular.text = strTelefono;
    
    [self retrieveClientDirection];
    
}

-(void) retrieveClientDirection{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0;
    NSArray *ArrayDireccion;
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    ArrayDireccion = [objDAO obtainDireccionCliente:intIdUsuario];
    
    if (ArrayDireccion.count > 0) {

        lblDireccion.text = [NSString stringWithFormat:@"%@ %@", ArrayDireccion[1], ArrayDireccion[2]];
 
        //make mutable string
        NSMutableString *stringToTrim = [ArrayDireccion[6] mutableCopy];
        
        //pass it by reference to CFStringTrimSpace
        CFStringTrimWhitespace((__bridge CFMutableStringRef) stringToTrim);
        
        lblComuna.text = [NSString stringWithFormat:@"%@, Santiago", stringToTrim];
        
        lblCiudad.text = @" ,Santiago";
        lblReferencia.text = ArrayDireccion[3];
    }
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

-(void) totalShoppingCart{
    
    NSArray *ArrayResumeShoppingCart;
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser = [objDAO obtainCurrentIdUser];
    
    if (intIdUser == -1) {
        intIdUser = 1;
    }
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUser];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        lblSubTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayResumeShoppingCart[0] doubleValue]]  ];
        //  lblDespacho.text = @"";
        lblTotal.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[ArrayResumeShoppingCart[0] doubleValue]]  ];
    }
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

-(void) retrieveFechasEntrega{

    [dataArray removeAllObjects];
    [dataArrayId removeAllObjects];
    
    dataArray = [[NSMutableArray alloc] init];
    dataArrayId = [[NSMutableArray alloc] init];
    
    //--------
    dao *objDAO = [[dao alloc] init];
    
    int intIdUsuario = 0;
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonDiasDespachodisponibles&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        NSLog(@"Load Fechas disponibles perfecto!!!");
        
        NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        newStr = [self stringByRemovingControlCharacters:newStr];
        
        NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
        
        //[{"intFecha":"20141115", "strFecha":"15/11/2014", "strDia":"Sábado" }]
        
        json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];

        [dataArrayId addObject:@"0"];
        [dataArray addObject:@"Seleccione Opción"];
        
        for (int i = 0; i<json.count; i++)
        {
            NSString * strIdFecha = [[json objectAtIndex:i] objectForKey:@"intFecha"];
            NSString * strDescriptionFecha = [NSString stringWithFormat:@"%@ %@", [[json objectAtIndex:i] objectForKey:@"strFecha"], [[json objectAtIndex:i] objectForKey:@"strDia"]];
            
            [dataArrayId addObject:strIdFecha];
            [dataArray addObject:strDescriptionFecha];
        }

//      [self.pickerView reloadComponent:0];
        
    }else{
        NSLog(@"Error");
    }

//  [self.pickerView reloadAllComponents];
    [self.pickerView reloadComponent:0];
    
    // Init the picker view.
    pickerView = [[UIPickerView alloc] init];
    
    // Set the delegate and datasource. Don't expect picker view to work
    // correctly if you don't set it.
    [pickerView setDataSource: self];
    [pickerView setDelegate: self];
    
    pickerView.showsSelectionIndicator = YES;
    
    [pickerView selectRow:2 inComponent:0 animated:YES];
    
}

/*
- (void) retrieveFechasEntrega{
    
    [dataArray removeAllObjects];
    [dataArrayId removeAllObjects];

    dataArray = [[NSMutableArray alloc] init];
    dataArrayId = [[NSMutableArray alloc] init];

    //--------
    dao *objDAO = [[dao alloc] init];
    
    int intIdUsuario = 0;
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonDiasDespachodisponibles&strIdUsuario=%i", intIdUsuario];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Fechas disponibles perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"intFecha":"20141115", "strFecha":"15/11/2014", "strDia":"Sábado" }]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
                 NSString * strIdFecha = [[json objectAtIndex:i] objectForKey:@"intFecha"];
                 NSString * strDescriptionFecha = [NSString stringWithFormat:@"%@ %@", [[json objectAtIndex:i] objectForKey:@"strFecha"], [[json objectAtIndex:i] objectForKey:@"strDia"]];
                 
                 [dataArrayId addObject:strIdFecha];
                 [dataArray addObject:strDescriptionFecha];

             }
             
             [self.pickerView reloadComponent:0];
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded Fechas disponibles.");
         }
         else if (error != nil){
             NSLog(@"Error Fechas disponibles = %@", error);
         }
     }];
    //--------
}
*/

- (void)viewWillAppear:(BOOL)animated {

    dao *objDAO = [[dao alloc] init];

    [objDAO deleteRegisterBack];
    [objDAO insertRegisterBack:1];
    
    [self.backBarButtonItem setImage:[UIImage imageNamed:@"icono_atras_transparente.png"]]; //icono_llamar.png
    
    [self retrieveDataSearch];
    
    [self totalShoppingCart];
    
    [self retrieveClient];

//Revisamos si en la variable de ambiente de la fecha de entrega tiene especificada la fecha de despacho
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *myString = [prefs stringForKey:@"strFechaEntrega"];
    
    if (![myString  isEqual: @"Sin especificar"])  {

        myString = [prefs stringForKey:@"strFechaEntregaDescription"];
        
        strFechaEntrega.text = myString;
    }
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backToRegister:(id)sender {
    
    [self performSegueWithIdentifier:@"segueRegisterArea" sender:nil];
}

- (IBAction)backToRegisterPageMethod:(id)sender {

    [self performSegueWithIdentifier:@"segueRegisterArea" sender:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"segueCheckOutFinish"])
    {
        NSLog(@"Segue !!!!!!!");
        
        dao *objDAO = [[dao alloc] init];
        
        [objDAO insertLoading];
        
    }
}

- (IBAction)showPickerFechaEntrega:(id)sender {

    viewPicker.hidden = NO;
    
    [self retrieveFechasEntrega];
    
}

- (IBAction)closePickerFechaDespacho:(id)sender {

    viewPicker.hidden = YES;
    
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    
    if ([strFechaEntrega.text  isEqual: @"Sin especificar"])  {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Debe definir una fecha de entrega para su compra."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return NO;
        
    }else{
    
        return YES;
    }
    
}


@end


